﻿namespace Commands
{
    using System.Collections.ObjectModel;
    using Framework;

    public class RegistrationController : PropertyChangedBase
    {
        private readonly IRegistrationService _service;
        private string _confirm;
        private string _email;
        private bool _isFormValid;
        private string _password;

        public RegistrationController(IRegistrationService service)
        {
            _service = service;
            ValidationErrors = new ObservableCollection<string>();
        }

        public ObservableCollection<string> ValidationErrors { get; private set; }

        public bool IsFormValid
        {
            get { return _isFormValid; }
            set
            {
                _isFormValid = value;
                RaisePropertyChanged("IsFormValid");
            }
        }

        public string Email
        {
            get { return _email; }
            set
            {
                _email = value;
                RaisePropertyChanged("Email");
                ValidateForm();
            }
        }

        public string Password
        {
            get { return _password; }
            set
            {
                _password = value;
                RaisePropertyChanged("Password");
                ValidateForm();
            }
        }

        public string Confirm
        {
            get { return _confirm; }
            set
            {
                _confirm = value;
                RaisePropertyChanged("Confirm");
                ValidateForm();
            }
        }

        public DelegatingCommand RegisterCommand
        {
            get
            {
                return Execute
                    .AsCommand(() => _service.Register("", Password))
                    .If(() => IsFormValid);
            }
        }

        public void ValidateForm()
        {
            if (ValidationErrors != null) ValidationErrors.Clear();
            IsFormValid = true;

            if (string.IsNullOrEmpty(Email))
                ReportProblem("Email cannot be blank.");

            if (string.IsNullOrEmpty(Password))
                ReportProblem("Password cannot be blank.");

            if (Password != Confirm)
                ReportProblem("Password and confirmation do not match.");
        }

        private void ReportProblem(string reason)
        {
            IsFormValid = false;
            ValidationErrors.Add(reason);
        }
    }
}